package com.stylefeng.guns.modular.mycity.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.GunsApplication;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.common.constant.cache.Cache;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.modular.mycity.MyCityDto;
import com.stylefeng.guns.modular.mycity.service.IMyCityService;
import com.stylefeng.guns.modular.system.model.MyCity;
import com.stylefeng.guns.modular.system.warpper.MyCityWarpper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 我的城市控制器
 *
 * @author fengshuonan
 * @Date 2018-09-21 14:10:13
 */
@Controller
@RequestMapping("/myCity")
public class MyCityController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(GunsApplication.class);

    private String PREFIX = "/mycity/myCity/";
    private String CachePREFIX = "sdmycity#";
    //特权账户
    private String[] PrivilegeAccount=new String[]{"admin","wangshuang","gaojianlong"};

    @Autowired
    private IMyCityService myCityService;

    /**
     * 跳转到我的城市首页
     */
    @RequestMapping("")
    public String index() {
        ShiroUser user = ShiroKit.getUser();
        System.out.println("user!!!!!!!!!!!!!!!!!!!"+user);
        //id=1, account='admin', name='张三', deptId=27, roleList=[1], deptName='战略部', roleNames=[超级管理员]
        return PREFIX + "myCity.html";
    }

    /**
     * 跳转到添加我的城市
     */
    @RequestMapping("/myCity_add")
    public String myCityAdd() {
        return PREFIX + "myCity_add.html";
    }

    /**
     * 跳转到修改我的城市
     */
    @RequestMapping("/myCity_update/{myCityId}")
    public String myCityUpdate(@PathVariable Integer myCityId, Model model) {
        MyCity myCity = myCityService.selectById(myCityId);
        model.addAttribute("item",myCity);
        LogObjectHolder.me().set(myCity);
        return PREFIX + "myCity_edit.html";
    }

    /**
     * 获取我的城市列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        EntityWrapper<MyCity> wrapper = new EntityWrapper<>();
        //如果不是特权账户的话,  只显示相应的城市
        if(!isPrivilegeAccount()){
            String city = getCity();
            wrapper.eq("city",city);
        }
        List<Map<String, Object>> myCities = myCityService.selectMaps(wrapper);
        Object warp = new MyCityWarpper(myCities).warp();
        return warp;
    }
    /**
     *外部获取我的城市列表,需要放开shiro认证
     */
    @RequestMapping(value = "/externalList")
    @ResponseBody
    public Object externalList(@RequestParam(value = "city",defaultValue = "jinan",required = false) String city) {
        ArrayList<MyCityDto> result = getlist(city);
        if(result!=null&&result.size()>0){
            return result;
        }
        //否则用济南的
        //BeanKit.beanToMap();
        result=   getlist("jinan");
        if(result==null){
            result=new ArrayList<MyCityDto>();
        }
        return result;

    }

    private  ArrayList<MyCityDto> getlist(String city){
        ArrayList<MyCityDto> result = null;
        result= ( ArrayList<MyCityDto>)CacheKit.get(Cache.CONSTANT, CachePREFIX + city);
        //缓存中有数据直接返回
        if(result!=null&&result.size()>0){
            return result;
        }
        //缓存中没有数据,查询数据库
        EntityWrapper<MyCity> wrapper = new EntityWrapper<>();
        //展示相应城市的已发布的条目
        wrapper.eq("city",city);
        wrapper.eq("examine",2);
        List<MyCity> myCities = myCityService.selectList(wrapper);
        if(myCities!=null&&myCities.size()>0){
            result=new ArrayList<MyCityDto>();
            for(MyCity myCity:myCities){
                MyCityDto dto = new MyCityDto();
                BeanUtils.copyProperties(myCity,dto);
                result.add(dto);
            }
            //放入缓存
            CacheKit.put(Cache.CONSTANT,CachePREFIX + city,result);
        }
        return result;
    }


    /**
     * 新增我的城市
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(MyCity myCity) {
        //如果不是特权账户,  将新增值中的城市名替换掉
        if(!isPrivilegeAccount()){
            String city=getCity();
            myCity.setCity(city);
        }
        myCityService.insert(myCity);
        return SUCCESS_TIP;
    }

    /**
     * 删除我的城市
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer myCityId) {
        String city = getCity();
        MyCity myCity = myCityService.selectById(myCityId);
        if(!isPrivilegeAccount()){
            //不是特权账户只能删除自己的地市数据
            if(!myCity.getCity().equals(city)){
                return new ErrorTip(401,"权限不足");
            }
        }
        if(myCity.getExamine()==2){
            return new ErrorTip(1002,"请先下架再删除");
        }
        myCityService.deleteById(myCityId);
        return SUCCESS_TIP;
    }

    /**
     * 修改我的城市
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(MyCity myCity) {
        //除了特权用户, 城市名都要被修改
        if(!isPrivilegeAccount()){
            String city=getCity();
            myCity.setCity(city);
        }
        //判断是否是上架数据 , 是的话不允许更改
        MyCity myCityInDatabase = myCityService.selectById(myCity.getId());
        if(myCityInDatabase.getExamine()==2){
            return new ErrorTip(1002,"请先下架再修改");
        }
        myCityService.updateById(myCity);
        return SUCCESS_TIP;
    }

    /**
     * 我的城市详情
     */
    @RequestMapping(value = "/detail/{myCityId}")
    @ResponseBody
    public Object detail(@PathVariable("myCityId") Integer myCityId) {
        return myCityService.selectById(myCityId);
    }
    /**
     * 我的城市发布
     */
    @RequestMapping(value = "/publish")
    @ResponseBody
    public Object publish(@RequestParam("myCityId") Integer myCityId) {
        System.out.println("我的城市发布------------myCityId = [" + myCityId + "]");

        MyCity myCity = myCityService.selectById(myCityId);
        if(!isPrivilegeAccount()){
            String city = getCity();
            //不是特权账户只能发布自己的地市数据
            if(!myCity.getCity().equals(city)){
                return new ErrorTip(401,"权限不足");
            }
        }
        //发布
        myCity.setExamine(2);
        myCityService.updateById(myCity);
        CacheKit.remove(Cache.CONSTANT,CachePREFIX+myCity.getCity());
        logger.info("上架删除缓存---"+myCity.getCity());
        return SUCCESS_TIP;
    }
    /**
     * 我的城市下架
     * 上架\下架操作要更新缓存,直接置空对应的键
     */
    @RequestMapping(value = "/offline")
    @ResponseBody
    public Object offline(@RequestParam("myCityId") Integer myCityId) {
        System.out.println("我的城市下架------------myCityId = [" + myCityId + "]");
        MyCity myCity = myCityService.selectById(myCityId);
        if(!isPrivilegeAccount()){
            String city = getCity();
            //不是特权账户只能发布自己的地市数据
            if(!myCity.getCity().equals(city)){
                return new ErrorTip(401,"权限不足");
            }
        }
        //下架
        myCity.setExamine(1);
        myCityService.updateById(myCity);
        //移除对应城市的缓存
        CacheKit.remove(Cache.CONSTANT,CachePREFIX+myCity.getCity());
        logger.info("下架删除缓存---"+myCity.getCity());
        return SUCCESS_TIP;
    }

    /**
     * 根据账户获得归属地市
     * @return
     */

    public String getCity(){
        String account = ShiroKit.getUser().getAccount();
        String[] splitAccount = account.split("-");
       return splitAccount[0];
    }

    /**
     * 判断当前用户是否是本项目的特权用户
     * @return
     */
    public boolean isPrivilegeAccount(){
        String currentAccount=ShiroKit.getUser().getAccount();
        for(String account:PrivilegeAccount){
            if(currentAccount.equals(account))
                return true;
        }
        return false;

    }


}
